#include "usermodel.hpp"
#include "connectionpool.h"

// User表的增加方法
bool UserModel::insert(User &user)
{
    char sql[1024] = {0};
    sprintf(sql, "insert into user(name, password, state) values('%s', '%s', '%s')",
        user.getName().c_str(), user.getPwd().c_str(), user.getState().c_str());

    {
        shared_ptr<MySQL> sp = cp->getConnection();
        if(sp->query(sql)) {
            user.setId(mysql_insert_id(sp->getConnection()));
            return true;
        }
    }

    return false;
}

// 根据用户号码查询用户信息
User UserModel::query(int id)
{
    char sql[1024] = {0};
    sprintf(sql, "select * from user where id = %d",id);

    MYSQL_RES *res = nullptr;
    {
        shared_ptr<MySQL> sp = cp->getConnection();
        res = sp->query(sql);
    }

    if (res != nullptr) {
        MYSQL_ROW row = mysql_fetch_row(res);
        if (row != nullptr) {
            User user;
            user.setId(atoi(row[0]));
            user.setName(row[1]);
            user.setPwd(row[2]);
            user.setState(row[3]);
            mysql_free_result(res);  // 释放资源
            return user;
        }
    }

    return User();
}

bool UserModel::updateState(User user)
{
    char sql[1024] = {0};
    sprintf(sql, "update user set state = '%s' where id = %d", user.getState().c_str(), user.getId());

    {
        shared_ptr<MySQL> sp = cp->getConnection();
        if(sp->query(sql)) {
            return true;
        }
    }

    return false;
}

// 重置用户状态
void UserModel::resetState()
{
    char sql[1024] = "update user set state = 'offline' where state = 'online'";

    shared_ptr<MySQL> sp = cp->getConnection();
    sp->update(sql);
}